package com.jjb.www.http.model;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import androidx.lifecycle.LifecycleOwner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.blankj.utilcode.util.GsonUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.hjq.http.body.JsonBody;
import com.jjb.www.R;
import com.jjb.www.manager.ActivityManager;
import com.jjb.www.ui.activity.LoginActivity;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.http.EasyLog;
import com.hjq.http.config.IRequestApi;
import com.hjq.http.config.IRequestHandler;
import com.hjq.http.exception.CancelException;
import com.hjq.http.exception.DataException;
import com.hjq.http.exception.HttpException;
import com.hjq.http.exception.NetworkException;
import com.hjq.http.exception.ResponseException;
import com.hjq.http.exception.ResultException;
import com.hjq.http.exception.ServerException;
import com.hjq.http.exception.TimeoutException;
import com.hjq.http.exception.TokenException;
import com.jjb.www.utils.AESUtils;
import com.tencent.mmkv.MMKV;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;

import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * author : Android CRG
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2019/12/07
 * desc   : 请求处理类
 */
public final class RequestHandler implements IRequestHandler {

    private final Application mApplication;
    private final MMKV mMmkv;

    public RequestHandler(Application application) {
        mApplication = application;
        mMmkv = MMKV.mmkvWithID("http_cache_id");
    }

    @Override
    public Object requestSucceed(LifecycleOwner lifecycle, IRequestApi api, Response response, Type type) throws Exception {

        if (Response.class.equals(type)) {
            return response;
        }

        if (!response.isSuccessful()) {
            // 返回响应异常
            throw new ResponseException(mApplication.getString(R.string.http_response_error) + "，responseCode：" + response.code() + "，message：" + response.message(), response);
        }

        if (Headers.class.equals(type)) {
            return response.headers();
        }

        ResponseBody body = response.body();
        if (body == null) {
            return null;
        }

        if (InputStream.class.equals(type)) {
            return body.byteStream();
        }

        String text;

//        String newText;
        try {
            text = body.string();
//            CommJsonModel commJsonModel = GsonFactory.getSingletonGson().fromJson(text, CommJsonModel.class);
//            HttpData httpData = new HttpData();
//            httpData.setCode(commJsonModel.getCode());
//            httpData.setMsg(commJsonModel.getMsg());
//            Object parsedJson = parseNewJson(AESUtils.decrypt(commJsonModel.getData()));
//            httpData.setData(parsedJson instanceof JSONObject ? ((JSONObject) parsedJson) : parsedJson);
//            newText = GsonUtils.toJson(httpData);
        } catch (IOException e) {
            // 返回结果读取异常
            throw new DataException(mApplication.getString(R.string.http_data_explain_error), e);
        }

        // 打印这个 Json 或者文本
        EasyLog.json(text);

        if (String.class.equals(type)) {
            return text;
        }

        if (JSONObject.class.equals(type)) {
            try {
                // 如果这是一个 JSONObject 对象
                return new JSONObject(text);
            } catch (JSONException e) {
                throw new DataException(mApplication.getString(R.string.http_data_explain_error), e);
            }
        }

        if (JSONArray.class.equals(type)) {
            try {
                // 如果这是一个 JSONArray 对象
                return new JSONArray(text);
            } catch (JSONException e) {
                throw new DataException(mApplication.getString(R.string.http_data_explain_error), e);
            }
        }

        final Object result;
        try {
            result = GsonFactory.getSingletonGson().fromJson(text, type);
        } catch (JsonSyntaxException e) {
            // 返回结果读取异常
            throw new DataException(mApplication.getString(R.string.http_data_explain_error), e);
        }

        if (result instanceof HttpData) {

            HttpData<?> model = (HttpData<?>) result;
            if (model.isRequestSucceed()) {
                // 代表执行成功
                return result;
            }

            if (model.isTokenFailure()) {
                // 代表登录失效，需要重新登录
                throw new TokenException(mApplication.getString(R.string.http_token_error));
            }

            // 代表执行失败
            throw new ResultException(model.getMsg(), model);
        }
        return result;
    }

    @Override
    public Exception requestFail(LifecycleOwner lifecycle, IRequestApi api, Exception e) {
        // 判断这个异常是不是自己抛的
        if (e instanceof HttpException) {
            if (e instanceof TokenException) {
                // 登录信息失效，跳转到登录页
                Application application = ActivityManager.getInstance().getApplication();
                Intent intent = new Intent(application, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                application.startActivity(intent);
                // 销毁除了登录页之外的 Activity
                ActivityManager.getInstance().finishAllActivities(LoginActivity.class);
            }
            return e;
        }

        if (e instanceof SocketTimeoutException) {
            return new TimeoutException(mApplication.getString(R.string.http_server_out_time), e);
        }

        if (e instanceof UnknownHostException) {
            NetworkInfo info = ((ConnectivityManager) mApplication.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            // 判断网络是否连接
            if (info == null || !info.isConnected()) {
                // 没有连接就是网络异常
                return new NetworkException(mApplication.getString(R.string.http_network_error), e);
            }

            // 有连接就是服务器的问题
            return new ServerException(mApplication.getString(R.string.http_server_error), e);
        }

        if (e instanceof IOException) {
            //e = new CancelException(context.getString(R.string.http_request_cancel), e);
            return new CancelException("", e);
        }

        return new HttpException(e.getMessage(), e);
    }

    @Override
    public Object readCache(LifecycleOwner lifecycle, IRequestApi api, Type type) {
        String cacheKey = GsonFactory.getSingletonGson().toJson(api);
        String cacheValue = mMmkv.getString(cacheKey, null);
        if (cacheValue == null || "".equals(cacheValue) || "{}".equals(cacheValue)) {
            return null;
        }
        EasyLog.print("---------- cacheKey ----------");
        EasyLog.json(cacheKey);
        EasyLog.print("---------- cacheValue ----------");
        EasyLog.json(cacheValue);
        return GsonFactory.getSingletonGson().fromJson(cacheValue, type);
    }

    @Override
    public boolean writeCache(LifecycleOwner lifecycle, IRequestApi api, Response response, Object result) {
        String cacheKey = GsonFactory.getSingletonGson().toJson(api);
        String cacheValue = GsonFactory.getSingletonGson().toJson(result);
        if (cacheValue == null || "".equals(cacheValue) || "{}".equals(cacheValue)) {
            return false;
        }
        EasyLog.print("---------- cacheKey ----------");
        EasyLog.json(cacheKey);
        EasyLog.print("---------- cacheValue ----------");
        EasyLog.json(cacheValue);
        return mMmkv.putString(cacheKey, cacheValue).commit();
    }
    public static Object parseNewJson(String jsonString) {
        // 使用 FastJSON 解析 JSON 字符串，保持字段顺序
        return JSON.parse(jsonString);
    }


    private static void handleJsonObject(JSONObject jsonObject) throws JSONException {
        // 获取JSONObject的所有键
        JSONArray keys = jsonObject.names();

        // 遍历所有键，然后根据类型进行处理
        for (int i = 0; i < keys.length(); i++) {
            String key = keys.getString(i);
            Object value = jsonObject.get(key);

            if (value instanceof String) {
                // 处理字符串
                System.out.println("Key: " + key + ", Value (String): " + value);
            } else if (value instanceof JSONArray) {
                // 处理数组
                System.out.println("Key: " + key + ", Value (Array): " + value);

                // 如果数组中有嵌套结构，可以进行递归处理
                handleNestedArray((JSONArray) value);
            } else if (value instanceof JSONObject) {
                // 处理嵌套的JSONObject
                System.out.println("Key: " + key + ", Value (Nested JSONObject): " + value);

                // 如果嵌套的JSONObject中有嵌套结构，可以进行递归处理
                handleJsonObject((JSONObject) value);
            } else {
                // 其他类型的值，可能是null等
                System.out.println("Key: " + key + ", Value: " + value);
            }
        }
    }

    private static void handleNestedArray(JSONArray array) throws JSONException {
        for (int i = 0; i < array.length(); i++) {
            Object element = array.get(i);

            if (element instanceof String) {
                // 处理数组中的字符串
                System.out.println("Array Element (String): " + element);
            } else if (element instanceof JSONArray) {
                // 处理数组中的嵌套数组
                handleNestedArray((JSONArray) element);
            } else if (element instanceof JSONObject) {
                // 处理数组中的嵌套JSONObject
                handleJsonObject((JSONObject) element);
            }
        }
    }

}